<?php
namespace Common\Logic;

/**
 * 组管理逻辑层
 * @modify trainyao 2016-07-26 创建
 */
class GroupLogic extends \Common\Controller\BaseController {

    /**
     * 根据用户ID获取所操作的组
     * @modify trainyao 2016-07-26 创建
     * @param  integer   $userId    管理员ID
     * @return array              组信息数组
     */
    public function getInfoByUser($userId) {
        return $this->__singleGet('_getInfoByUser', array($userId));
    }
    protected function _getInfoByUser($userId) {
        $groupInfoModel = D('GroupInfo');
        return $groupInfoModel->getInfoByUser($userId);
    }

    /**
     * 检查是否可以操作组
     * @modify trainyao 2016-07-26 创建
     * @param  integer   $userId    用户ID
     * @param  mixin   $groupId   组ID(s)
     * @return boolean              是否可以操作
     */
    public function check($userId, $groupId) {
        if (!is_array($groupId)) {
            $groupId = explode(',', $groupId);
        }

        $groupInfo = $this->getInfoByUser($userId);
        return empty(array_diff($groupId, array_column($groupInfo, 'id')));
    }

    /**
     * 检查是否能加入组内
     * 方法会抛异常,已存在别的组的情况 Exception::getCode返回已存在别的组的adminLoginId
     * @modify trainyao 2016-07-26    创建
     * @param  integer   $groupId      组ID
     * @param  mixin   $adminLoginId 子管理员ID(s)
     * @return boolean                是否能加入组内
     */
    public function checkCanAddInGroup($groupId, $adminLoginId) {
        if (!is_array($adminLoginId)) {
            $adminLoginId = explode(',', $adminLoginId);
        }

        $userId = getUserId();
        $accountLogic = A('Common/Account', 'Logic');
        $adminInfo = $accountLogic->getSub($userId);
        $adminInfo = getArrayValueAsIndex($adminInfo, 'id');

        foreach ($adminLoginId as $adminLoginIdItem) {
            if ($adminInfo[$adminLoginIdItem]['groupId'] != 0 && $adminInfo[$adminLoginIdItem]['groupId'] != $groupId) {
                throw new \Exception('403,210', (int)$adminLoginIdItem);
                return false;
            }
        }
        unset($adminLoginIdItem);
        
        return true;
    }

    /**
     * 保存组信息
     * 方法会抛异常
     * @modify trainyao 2016-07-26 创建
     * @param  Array    $infoArray 组信息 {id, name}
     * @return boolean              执行结果
     */
    public function saveInfo(Array $infoArray, $userId) {
        // 获取现有的组,筛选出新增的组,需要修改的组
        $groupToAdd = array();
        $groupToEdit = array();
        $groupInfo = getArrayValueAsIndex($this->getInfoByUser($userId), 'id');
        foreach ($infoArray as $index => $groupInfoArray) {
            if ($groupInfoArray['id'] == 0) {
                array_push($groupToAdd, array(
                    'name' => $groupInfoArray['name'],
                    'adminlogin_id' => $userId,
                    'creator' => $userId,
                    'operator' => $userId,
                ));
                unset($infoArray[$index]);
                continue;
            } else {
                if ($groupInfoArray['name'] != $groupInfo[$groupInfoArray['id']]['name']) {
                    array_push($groupToEdit, $groupInfoArray);
                }
                continue;
            }
        }
        unset($groupInfoArray);

        // 对比数据库不存在的ID,infoArray储存为需要删除的组ID
        $infoArray = array_values(array_diff(array_column($groupInfo, 'id'), array_column($infoArray, 'id')));

        // 新增组
        $groupInfoModel = D('GroupInfo');
        $groupInfoModel->startTrans();
        $commit = true;
        if (!empty($groupToAdd)) {
            $result = $groupInfoModel->addInfo($groupToAdd);
            if (empty($result)) {
                $commit = false;
            }
        }

        // 保存组
        if ($commit && !empty($groupToEdit)) {
            foreach ($groupToEdit as $groupToEditItem) {
                $result = $groupInfoModel->saveInfo($groupToEditItem['id'], $groupToEditItem['name']);
                if (empty($result)) {
                    $commit = false;
                    break;
                }
            }
            unset($groupToEditItem);
        }

        // 删除组
        if ($commit && !empty($infoArray)) {
            $result = $groupInfoModel->deleteInfo($infoArray);
            if (empty($result)) {
                $commit = false;
            }

            // 删除组-子管理员关系
            if ($commit) {
                $groupAdminModel = D('GroupAdmin');
                $result = $groupAdminModel->deleteInfoByGroupAdmin($infoArray);
                if (empty($result)) {
                    $commit = false;
                }
            }
        }

        if ($commit) {
            $groupInfoModel->commit();
            return true;
        } else {
            $groupInfoModel->rollback();
            throw new \Exception("500,506", 506);
            return false;
        }
    }

    /**
     * 保存组内子管理员状态
     * 方法会抛异常
     * @modify trainyao 2016-07-26           创建
     * @param  integer   $groupId             组ID
     * @param  Array    $inGroupAccountId    在组内的子管理员ID
     * @param  Array    $notInGroupAccountId 不在组内的子管理员ID
     */
    public function saveAccount($groupId, Array $inGroupAccountId, Array $notInGroupAccountId) {
        $groupAdminModel = D('GroupAdmin');
        $dbInGroupAdminLoginIds = $groupAdminModel->getInfoByGroup($groupId);
        $dbInGroupAdminLoginIds = array_column($dbInGroupAdminLoginIds, 'adminlogin_id');

        // 筛选出需要增加的ID
        $groupAdminToAdd = array_diff($inGroupAccountId, $dbInGroupAdminLoginIds);
        
        // 添加
        $groupAdminModel->startTrans();
        $commit = true;
        if (!empty($groupAdminToAdd)) {
            $result = $groupAdminModel->addInfoByGroup($groupId, $groupAdminToAdd);
            if (empty($result)) {
                $commit = false;
            }
        }

        // 删除
        if ($commit && !empty($notInGroupAccountId)) {
            $result = $groupAdminModel->deleteInfoByGroupAdmin($groupId, $notInGroupAccountId);
            if (empty($result)) {
                $commit = false;
            }
        }

        if ($commit) {
            $groupAdminModel->commit();
            return true;
        } else {
            $groupAdminModel->rollback();
            throw new \Exception('500,506', 506);
            return false;
        }
    }
}
